package com.snow.useviewdemo.lyric;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.os.Handler;
import androidx.appcompat.widget.AppCompatTextView;
import android.util.AttributeSet;

public class MyView extends AppCompatTextView {

    private float float1 = 0.0f;
    private float float2 = 0.01f;
    private Handler handler;
    private String text;
    public static int count = 0;

    public MyView(Context context) {
        this(context, null);

    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        handler = new Handler();
        text = "对于美方发起的贸易战，中国早就表明态度：";

        update.run();
    }

    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        float1 += 0.001f;
        float2 += 0.001f;
        count++;
        if (float2 > 1.0) {
            float1 = 0.0f;
            float2 = 0.01f;
        }
//        this.setTextSize(50);
        Paint paint = new Paint();
        paint.setTextSize(50);
        float len = this.getTextSize() * text.length();
        int[] a = new int[]{Color.RED, Color.BLACK};
        //Shader shader = new LinearGradient(0, 0, len, 0, new int[]{Color.YELLOW, Color.RED},
        //                new float[]{float1, float2}, TileMode.CLAMP);
        float[] f = new float[]{float1, float2};
        Shader shader = new LinearGradient(0, 0, len, 0, a, f, TileMode.CLAMP);
        paint.setShader(shader);
        canvas.drawText(text, 0, 70, paint);
    }

    private Runnable update = new Runnable() {

        @Override
        public void run() {
            MyView.this.update();
            handler.postDelayed(update, 10);
        }

    };

    private void update() {
        postInvalidate();
    }
}
